using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using mshtml;


namespace hosted_gmail_client
{
    public partial class Frame : Form
    {
        private string password;
        private string emailaddress;
        private bool hide = true;
        private int numtries = 0;
        private int secondsloading = 0;
        private Timer loadingtimer = new Timer();

        public Frame()
        {
            InitializeComponent();
        }

        #region "Events"
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            ShowApplication();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (Options frmOptions = new Options())
            {
                frmOptions.ShowDialog();
                if (frmOptions.AccountChanged && frmOptions.DialogResult == DialogResult.OK)
                {
                    Logout frmLogOut = new Logout(1);
                    Logout frmLogOut2 = new Logout(2);
                    frmLogOut.ShowDialog();
                    frmLogOut2.ShowDialog();
                    if (frmLogOut.DialogResult == DialogResult.OK && frmLogOut2.DialogResult == DialogResult.OK)
                    {
                        numtries = 0;
                        GetRegistryValues();
                        LoadContent();
                    }
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QuitApplication();
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            QuitApplication();
        }

        private void documentationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Not yet implemented");
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Not yet implemented");
        }

        private void showToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowApplication();
        }

        private void Frame_Load(object sender, EventArgs e)
        {
            loadingtimer.Tick += new System.EventHandler(this.loadingtimer_Tick);
            using (RegistryKey key = Common.GetRegistryKey(false))
            {
                if (key.GetValue("emailaddress") != null && key.GetValue("password") != null)
                {
                    GetRegistryValues();

                    if (Common.AuthenticateUser(emailaddress, password))
                        LoadContent();
                    else
                        ShowLoginScreen();

                }
                else
                    ShowLoginScreen();
            }
        }

        private void Frame_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (hide)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void wbGmail_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (wbGmail.Document.GetElementById("userName") != null)
            {
                //auto-fill login screen for Gmail with registry values
                wbGmail.Document.GetElementById("userName").SetAttribute("value", emailaddress.Split(Char.Parse("@"))[0]);
                wbGmail.Document.GetElementById("password").SetAttribute("value", password);

                //auto-fill login screen for Google calendar with registry settinsg
                wbCalendar.Document.GetElementById("userName").SetAttribute("value", emailaddress.Split(Char.Parse("@"))[0]);
                wbCalendar.Document.GetElementById("password").SetAttribute("value", password);

                if (numtries < 2)
                {
                    //auto-submit gmail login page
                    mshtml.IHTMLWindow2 gmail = (mshtml.IHTMLWindow2)wbGmail.Document.Window.DomWindow;
                    gmail.execScript("document.forms[0].submit();", "javascript");

                    //auto-submit gcalendar login page
                    mshtml.IHTMLWindow2 gcalendar = (mshtml.IHTMLWindow2)wbCalendar.Document.Window.DomWindow;
                    gcalendar.execScript("document.forms[0].submit();", "javascript");

                    numtries++;
                }
            }
            if (wbGmail.Document.GetElementById("userName") == null && wbCalendar.Document.GetElementById("password") == null)
            {
                ShowLoading(false);
                numtries = 0;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LoadContent();
            ShowRetryLinks(false);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LoadContent();
            ShowRetryLinks(false);
        }

        private void loadingtimer_Tick(object sender, EventArgs e)
        {
            secondsloading++;
            if (secondsloading > 10)
            {
                ShowRetryLinks(true);
            }
        }

        #endregion

        private void GetRegistryValues()
        {
            using (RegistryKey key = Common.GetRegistryKey(false))
            {
                emailaddress = (string)key.GetValue("emailaddress");
                password = (string)key.GetValue("password");
            }
        }

        private void LoadContent()
        {
            ShowLoading(true);
            wbGmail.Navigate("http://mail.google.com/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/");
            wbCalendar.Navigate("http://www.google.com/calendar/hosted/" + emailaddress.Split(Char.Parse("@"))[1].ToString() + "/");
        }

        private void ShowLoginScreen()
        {
            using (Login frmLogin = new Login())
            {
                frmLogin.ShowDialog();
                GetRegistryValues();

                if (frmLogin.DialogResult == DialogResult.OK)
                    LoadContent();
                else
                    QuitApplication();
            }
        }

        private void QuitApplication()
        {
            hide = false;
            Application.Exit();
        }

        private void ShowApplication()
        {
            this.Show();
            this.Activate();

            if (this.WindowState == FormWindowState.Minimized)
                this.WindowState = FormWindowState.Normal;
        }

        private void ShowLoading(bool show)
        {
            pnlLoading.Visible = show;
            pnlLoading2.Visible = show;

            if (show)
            {
                ShowRetryLinks(false);
                loadingtimer.Interval = 1000;
                loadingtimer.Start();
            }
            else
            {
                loadingtimer.Stop();
                secondsloading = 0;
            }
        }


        private void ShowRetryLinks(bool show)
        {
            lnkRetry.Visible = show;
            lnkRetry1.Visible = show;
            secondsloading = 0;
        }
    }
}